package com.wxjfkg.workflow.impl;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import com.fivestar.loan.service.vo.ProdConstants;
import org.activiti.engine.delegate.DelegateExecution;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.fivestar.credit.service.ApplyCreditService;
import com.fivestar.credit.service.CreditApplyInfoService;
import com.fivestar.credit.service.vo.ApplyCredDiscountDto;
import com.fivestar.credit.service.vo.ApplyCredRelateDto;
import com.fivestar.credit.service.vo.ApplyCredTakeDto;
import com.fivestar.credit.service.vo.ApplyCredTakeImageDto;
import com.fivestar.credit.service.vo.CreditApplyInfoDto;
import com.fivestar.credit.service.vo.CreditApplyInfoImageDto;
import com.fivestar.credit.service.vo.CreditConstants;
import com.fivestar.loan.service.vo.ApplyConstants;
import com.fivestar.merchant.service.MerchQryService;
import com.fivestar.merchant.service.vo.MerchantConstants;
import com.fivestar.merchant.service.vo.MerchantImagesDto;
import com.fivestar.merchant.service.vo.MerchantInfoDto;
import com.fivestar.query.vo.ResultDto;
import com.fivestar.util.str.StringUtils;
import com.fivestar.xbk.service.XbkWorkOrderService;
import com.fivestar.xbk.service.vo.XbkConstants;
import com.fivestar.xbk.service.vo.XbkWorkOrderActionDto;
import com.fivestar.xbk.service.vo.XbkWorkOrderDto;
import com.wxjfkg.workflow.BeforeEndTaskService;


@Service("workorderSuccessTaskService")
public class WorkorderSuccessTaskServiceImpl implements BeforeEndTaskService {

	public Logger logger = LoggerFactory.getLogger(WorkorderFailTaskServiceImpl.class);
	
	@Autowired
	private XbkWorkOrderService xbkWorkOrderService;
	@Autowired
	private MerchQryService merchQryService;
	@Autowired
	private CreditApplyInfoService creditApplyInfoService;
	@Autowired
	private ApplyCreditService applyCreditService;
	
	@Override
	@Transactional(value="txTranManager")
	public void execute(DelegateExecution execution) throws Exception {
		String businessKey = execution.getProcessBusinessKey();
		if(!StringUtils.isEmpty(businessKey)){
			XbkWorkOrderDto workOrderDto = new XbkWorkOrderDto();
			workOrderDto.setOrderCode(businessKey);
			workOrderDto = xbkWorkOrderService.queryWorkOrder(workOrderDto);
			if(workOrderDto==null){
				logger.error("根据工单编号[orderId]="+businessKey+"查询不到工单信息");
				return;
			}
			workOrderDto.setOpStatus(XbkConstants.ORDER_STATE.FINISH);
			Boolean flag = xbkWorkOrderService.updateOrderByCode(workOrderDto);
			if(flag){
				logger.info("根据工单编号[orderId]="+businessKey+"的工单状态成功");
			}else{
				logger.error("根据工单编号[orderId]="+businessKey+"的工单状态失败");
				throw new Exception("根据工单编号[orderId]="+businessKey+"的工单状态失败");
			}
			//查询工单事件明细
			List<XbkWorkOrderActionDto> actionDtos=xbkWorkOrderService
					.queryWorkOrderAction(workOrderDto.getOrderCode() , false);
			if(XbkConstants.ORDER_TYPE.SIGN.equals(workOrderDto.getOrderType())){
				//会员店自动升级
				if(!StringUtils.isEmpty(workOrderDto.getMerchId())){
					MerchantInfoDto qryDto=new MerchantInfoDto();
					qryDto.setMerchId(workOrderDto.getMerchId());
					qryDto.setMerchLevel(MerchantConstants.MERCH_LEVEL.ZHS);
					boolean _flag=merchQryService.updateMerchant(qryDto);
					if(_flag){
						logger.info("更新正式会员店等级成功");
					}else{
						logger.info("更新正式会员店等级失败");
						throw new Exception("更新正式会员店等级失败");
					}
					if(actionDtos!=null&&!actionDtos.isEmpty()){
						MerchantImagesDto imageDto = new MerchantImagesDto();
						imageDto.setMerchId(workOrderDto.getMerchId());
						for(XbkWorkOrderActionDto ac :actionDtos){
							if(XbkConstants.ACTION_DETAIL.merchRioHandImg.equals(ac.getFieldKey())){
								imageDto.setMerchLegalImg4(ac.getFieldValue());
								continue;
							}
							if(XbkConstants.ACTION_DETAIL.merchRioImg.equals(ac.getFieldKey())){
								imageDto.setMerchRioImg(ac.getFieldValue());
								continue;
							}
						}
						boolean _flag2 = false;
						if(!StringUtils.isEmpty(imageDto.getMerchLegalImg4())
								||!StringUtils.isEmpty(imageDto.getMerchRioImg())){
							
							_flag2 = merchQryService.updateMerchantImg(imageDto);
						}
						if(_flag2){
							logger.info("更新会员店影像资料成功");
						}
					}
				}
			}else if(XbkConstants.ORDER_TYPE.LOAN.equals(workOrderDto.getOrderType())){
				// 星宝贝A授信、星宝贝B授信
				if(workOrderDto.getProdCode().contains(CreditConstants.CREDIT_TYPE_DSC.LOAN_CREDIT)){
					CreditApplyInfoDto creditApplyInfoDto = new CreditApplyInfoDto();
					creditApplyInfoDto.setApplyPersonId(workOrderDto.getMerchId());
					if(workOrderDto.getCustType().equals(XbkConstants.CUST_TYPE.MERCHANT)){
						creditApplyInfoDto.setApplyPersonType(CreditConstants.APPLY_PERSON_TYPE.MERCHANT);
					}else{
						creditApplyInfoDto.setApplyPersonType(CreditConstants.APPLY_PERSON_TYPE.PERSON);
					}
					creditApplyInfoDto.setOrderCode(workOrderDto.getOrderCode());
					creditApplyInfoDto.setApplyName(workOrderDto.getOrderContent());
					creditApplyInfoDto.setCredappDate(new Date());
					creditApplyInfoDto.setApplyChannel(CreditConstants.APPLY_CHANNEL.XBK);
					creditApplyInfoDto.setCreditType(workOrderDto.getCreditType());
					List<CreditApplyInfoImageDto> images = new ArrayList<CreditApplyInfoImageDto>();
					if(actionDtos!=null&&!actionDtos.isEmpty()){
						for(XbkWorkOrderActionDto ac : actionDtos){
							CreditApplyInfoImageDto image = new CreditApplyInfoImageDto();
							image.setImgType(ac.getFieldKey());
							image.setImgName(ac.getFieldName());
							image.setImgUrl(ac.getFieldValue());
							images.add(image);
						}
					}
					creditApplyInfoDto.setCreditApplyInfoImageDto(images);
					ResultDto<Boolean> result=creditApplyInfoService.createCreditApplyInfo(creditApplyInfoDto);
					if(result.isSuccess()&&result.getData()){
						logger.info(workOrderDto.getProdCode()+"生成授信申请信息成功");
					}else{
						logger.error(workOrderDto.getProdCode()+"生成授信申请信息失败");
						throw new Exception(workOrderDto.getProdCode()+"生成授信申请信息失败");
					}
				}
				// 星宝贝A用信、星宝贝B用信
				if(workOrderDto.getProdCode().contains(CreditConstants.CREDIT_TYPE_DSC.LOAN_USE)){
					ApplyCredDiscountDto applyDto = new ApplyCredDiscountDto();
					List<ApplyCredRelateDto> ious = new ArrayList<ApplyCredRelateDto>();
					List<ApplyCredTakeImageDto> images = new ArrayList<ApplyCredTakeImageDto>();
					ApplyCredTakeDto applyCredTakeDto = new ApplyCredTakeDto();
					List<String> prodIds = new ArrayList<>();
					prodIds.add(workOrderDto.getProdCode());
					applyCredTakeDto.setProdIds(prodIds);
//					applyCredTakeDto.setProdId(workOrderDto.getProdCode());
					applyCredTakeDto.setMerchId(workOrderDto.getMerchId());
					applyCredTakeDto.setApplyChannel(ApplyConstants.APPLY_SOURCE_FROM.XBK);
			        //贷款用途
					if(ProdConstants.PROD_CODE.LOAN_A_USE_NQ.equals(workOrderDto.getProdCode())) {
						applyCredTakeDto.setLoanUse(CreditConstants.CREDIT_USE_TYPE.NQ);
					}
					else if(ProdConstants.PROD_CODE.LOAN_A_USE_JH.equals(workOrderDto.getProdCode())) {
						applyCredTakeDto.setLoanUse(CreditConstants.CREDIT_USE_TYPE.JH);
					}
					if(actionDtos!=null&&!actionDtos.isEmpty()){
						for(XbkWorkOrderActionDto ac : actionDtos){
							if(XbkConstants.ACTION_TYPE.TEXT.equals(ac.getFieldType())){
								//====星白条用信====
								if(XbkConstants.ACTION_DETAIL.ApplyAmount
										.equals(ac.getFieldKey())){
									applyCredTakeDto.setApplyAmt(new BigDecimal(ac.getFieldValue()));
								}
								if(XbkConstants.ACTION_DETAIL.ApplyTerm
										.equals(ac.getFieldKey())){
									applyCredTakeDto.setApplyTerm(Integer.parseInt(ac.getFieldValue()));
								}
								if(XbkConstants.ACTION_DETAIL.ApplyIou
										.equals(ac.getFieldKey())){
									ApplyCredRelateDto relate = new ApplyCredRelateDto();
									relate.setIouCode(ac.getFieldValue());
									ious.add(relate);
								}
								//====星白条用信====
							}else{
								ApplyCredTakeImageDto image = new ApplyCredTakeImageDto();
								image.setImgKey(ac.getFieldKey());
								image.setImgName(ac.getFieldName());
								image.setImgUrl(ac.getFieldValue());
								images.add(image);
							}
							
						}
					}
					applyDto.setApplyCredTakeDto(applyCredTakeDto);
					applyDto.setApplyCredRelateDto(ious);
					applyDto.setApplyCredTakeImageDto(images);
					//生成用信申请信息
					ResultDto<Boolean> dto = applyCreditService.createApplyCreditList(applyDto,false);
					if(dto==null||!dto.isSuccess()||!dto.getData()){
						logger.error(dto.getMsg());
						throw new Exception(dto.getMsg());
					}
				}
			}
		}else{
			logger.error("工单编号[orderId]为空");
		}
	}

}
